package com.macbulldev.poc.testgin.service;



import java.util.Date;

import net.youngdev.util.encryption.MD5Util;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;

public class AppUserAuthenticationProvider  implements AuthenticationProvider
{
		private static final Logger LOGGER = Logger.getLogger(AppUserAuthenticationProvider.class);

				
		public AppUserAuthenticationProvider() 
		{
			super();
		}

		public Authentication authenticate(Authentication token)
				throws AuthenticationException {
			AppUser auth = null;
			String username =null;
			try
			{
				username = token.getName();
				String password = (String)token.getCredentials();
				//LOGGER.error("password="+password);
				password=MD5Util.getMD5Base64WithLabel(password);
				
				//LOGGER.error("password=["+password+"]");
				LOGGER.error("username=["+username+"]");
				LOGGER.error("calling authenticate() Principal:"+token.getPrincipal()+" name:"+token.getName()+" ");

				AppUser user = AppUser.getByEmailandPassword(username, password);
//				AppUser user = AppUser.findAppUser(username);
				if (user !=null && user.getPassword() !=null
						&& user.getPassword().trim().equals(password.trim()) 
						&& user.getPassword().startsWith(MD5Util.MD5_PREFIX)
						&& user.getPassword().length()>MD5Util.MD5_PREFIX.length())
				{
					//LOGGER.debug("returning "+user.toString());
					auth=user;
					
					EventLog evl = new EventLog();
					evl.setCreateTs(new Date());
					evl.setCreateUsername(auth.getName());
					evl.setObjectClass(AppUser.class.getSimpleName());
					evl.setOperation("login" );
					evl.persist();
				}
				else
				{
					LOGGER.debug("user is null");
				}
				
			}
			catch (Exception e)
			{
				LOGGER.error("Exception caught authenticating "+username,e);
			}		

			if (auth==null)
			{
				throw new AuthenticationCredentialsNotFoundException("Credentials returned no valid user");		
			}
			return auth;
		}

		public boolean supports(Class authentication) 
		{
			// org.springframework.security.providers.UsernamePasswordAuthenticationToken
//			System.out.println("calling supports() retValue="
//					+(Auth.class.isAssignableFrom(authentication))
//					+" authenticaiton class= "+authentication.getCanonicalName());
			LOGGER.error("calling supports()");
			return true;

		}

		
		
	}

